package cn.yitun.chat.yitunchatbasesdk.server.im.dispatcher.handler.impl;

import cn.yitun.chat.yitunactiondispatch.ActionDispatcher;
import cn.yitun.chat.yitunactiondispatch.extend.ActionResponse;
import cn.yitun.chat.yitunactiondispatch.extend.ArgumentBox;
import cn.yitun.chat.yitunchatbasesdk.server.im.dispatcher.handler.SessionMessageHandler;
import cn.yitun.chat.yitunnetsession.session.SocketSession;

/**
 * 
 * Date 2019-01-17 21:48:32<br>
 * Description 处理消息，并调度方法
 * @author yitun<br>
 * @since 1.1
 */
public class SessionMessageHandlerImpl extends BaseMessageHandlerImpl implements SessionMessageHandler {

	public SessionMessageHandlerImpl(ActionDispatcher actionDispatcher) {
		super(actionDispatcher);
	}

	@Override
	public void onMessage(String message, SocketSession socketSession) {
		onMessage(message, null, socketSession);
	}

	@Override
	public void onMessage(String message, String path, SocketSession socketSession) {
		Object result = doMessage(message, path, socketSession);
		write(socketSession, result);
	}

	@Override
	public Object doMessage(String message, SocketSession socketSession) {
		return doMessage(message, null, socketSession);
	}

	@Override
	public Object doMessage(String message, String path, SocketSession socketSession) {
		// AtomicReference<Object> responseData = new AtomicReference<>();
		ActionResponse actionResponse = new ActionResponse() {

			@Override
			public void write(Object data) {
				SessionMessageHandlerImpl.this.write(socketSession, data);
			}
		};
//		log.info(socketSession.getId());
//		log.info(socketSession.getKey() == null ? "" : socketSession.getKey().toString());
		ArgumentBox argumentBox = getArgumentBox();
		argumentBox.put(SocketSession.class, socketSession);
		return doMessage(message, path, actionResponse, argumentBox);
	}

	private void write(SocketSession socketSession, Object object) {
		if (null != object) {
			socketSession.write(object);
		}
	}
}
